<template>
  <view class="container page-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="nav">
        <view class="left">
          <view @click="handleBack">
            <uni-icons type="back" size="20" color="#333"></uni-icons>
          </view>
          <view @click="handleHome">
            <uni-icons type="home" size="20" color="#333"></uni-icons>
          </view>
        </view>
        <view class="title">健康资讯</view>
        <view class="right">
          <uni-icons type="more-filled" size="20" color="#333"></uni-icons>
          <uni-icons type="forward" size="20" color="#333"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 内容区域 -->
    <scroll-view 
      class="content" 
      scroll-y 
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
      v-if="articleData"
    >
      <view class="article-list">
        <view class="article-item">
          <view class="article-header">
            <image 
              class="article-image" 
              :src="articleData.image || defaultImage" 
              mode="aspectFill"
              @error="handleImageError"
            ></image>
            <view class="article-info">
              <view class="article-title">{{ articleData.title }}</view>
              <view class="article-meta">
                <text class="date">{{ articleData.time }}</text>
                <text class="reads">{{ articleData.views }}阅读</text>
              </view>
            </view>
          </view>
          <view class="article-content">
            <view class="content-text" v-html="formattedContent"></view>
            <image 
              v-if="articleData.image" 
              class="content-image" 
              :src="articleData.image" 
              mode="aspectFill"
              @error="handleImageError"
            ></image>
            <view class="comments-section">
              <view class="comments-header" @click="toggleComments">
                <view class="comments-title">{{ commentCountDisplay }}</view>
                <uni-icons :type="isCommentsVisible ? 'top' : 'bottom'" size="16" color="#666666"></uni-icons>
              </view>
              <view v-show="isCommentsVisible" class="comment-list">
                <view v-for="comment in comments" :key="comment.id" class="comment-item">
                  <view class="comment-main" @click="handleReply(comment)">
                    <image 
                      class="comment-avatar" 
                      :src="comment.avatar" 
                      mode="aspectFill"
                      @error="handleImageError"
                    ></image>
                    <view class="comment-content">
                      <view class="comment-user">
                        {{ comment.user }}
                        <text v-if="isCurrentUser(comment.userId)" class="user-self-tag">·我</text>
                      </view>
                      <view class="comment-text">{{ comment.content }}</view>
                      <view class="comment-time">{{ comment.time }}</view>
                      
                      <view class="comment-actions">
                        <view class="action-btn" @click.stop="handleLike(comment)">
                          <uni-icons 
                            :type="comment.isLiked ? 'heart-filled' : 'heart'" 
                            size="16" 
                            :color="comment.isLiked ? '#ff4d4f' : '#999'"
                          ></uni-icons>
                          <text>{{ comment.likes }}</text>
                        </view>
                        <text 
                          v-if="isCurrentUser(comment.userId)" 
                          class="delete-btn" 
                          @click.stop="handleDelete(comment)"
                        >删除</text>
                      </view>
                    </view>
                  </view>

                  <!-- 回复列表 -->
                  <view v-if="comment.replies.length > 0" class="replies-list">
                    <view v-for="reply in comment.replies" :key="reply.id" class="reply-item">
                      <view class="reply-main" @click="handleReply(reply, comment)">
                        <image 
                          class="reply-avatar" 
                          :src="reply.avatar" 
                          mode="aspectFill"
                          @error="handleImageError"
                        ></image>
                        <view class="reply-content">
                          <view class="reply-user">
                            {{ reply.user }}
                            <text v-if="isCurrentUser(reply.userId)" class="user-self-tag">·我</text>
                          </view>
                          <view class="reply-text">
                            <template v-if="!isReplyingSelf(reply, comment)">
                              <text class="reply-arrow">回复</text>
                              <text class="reply-target">{{ reply.replyTo || comment.user }}</text>
                              <text>: </text>
                            </template>
                            <text>{{ reply.content }}</text>
                          </view>
                          <view class="reply-time">{{ reply.time }}</view>
                          <view class="reply-actions">
                            <view class="like-btn" @click.stop="handleLike(reply)">
                              <uni-icons 
                                :type="reply.isLiked ? 'heart-filled' : 'heart'" 
                                size="16" 
                                :color="reply.isLiked ? '#ff4d4f' : '#999'"
                              ></uni-icons>
                              <text>{{ reply.likes }}</text>
                            </view>
                            <text 
                              v-if="isCurrentUser(reply.userId)" 
                              class="delete-btn" 
                              @click.stop="handleDeleteReply(reply, comment)"
                            >删除</text>
                          </view>
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
              </view>

              <view v-show="isCommentsVisible" class="comment-input">
                <view v-if="replyTo" class="reply-info">
                  <text>回复 {{ replyTo.user }} 的评论</text>
                  <text class="cancel-reply" @click="cancelReply">取消</text>
                </view>
                <view class="input-wrapper">
                  <input 
                    type="text" 
                    v-model="commentText" 
                    :placeholder="replyTo ? `回复 ${replyTo.user}...` : '写下你的评论...'" 
                    class="input-box"
                    @confirm="sendComment"
                    :focus="isInputFocus"
                    @focus="handleInputFocus"
                    @blur="handleInputBlur"
                  />
                  <button 
                    class="send-button" 
                    @click="sendComment"
                    :disabled="!commentText.trim()"
                  >发送</button>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 加载提示 -->
    <view v-else class="loading">
      <uni-icons type="loading" size="24" color="#999"></uni-icons>
      <text>加载中...</text>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import { apiBaseUrl, minioBaseUrl } from '../../../config/api'

// 声明 uni 类型
declare const uni: {
  navigateBack(): void;
  switchTab(options: { url: string }): void;
  navigateTo(options: { url: string }): void;
  showToast(options: { 
    title: string; 
    icon?: string;
    duration?: number;
  }): void;
  showModal(options: { 
    title: string; 
    content: string;
    confirmText?: string;
    cancelText?: string;
    success?: (res: { confirm: boolean }) => void;
  }): void;
  request(options: {
    url: string;
    method?: string;
    data?: any;
    header?: object;
    success?: (res: any) => void;
    fail?: (err: any) => void;
    complete?: () => void;
  }): void;
  getStorage(options: {
    key: string;
    success?: (res: { data: any }) => void;
  }): void;
  getStorageSync(key: string): any;
  setStorageSync(key: string, data: any): void;
}

// 声明 getCurrentPages 函数
declare function getCurrentPages(): Array<{
  options: Record<string, string>;
  route: string;
  [key: string]: any;
}>;

// 类型定义
interface Article {
  id: number
  title: string
  moredescription?: string
  more_description?: string
  image: string
  time: string
  views: string
}

interface Comment {
  id: number
  user: string
  userId: number
  avatar: string
  content: string
  time: string
  likes: number
  isLiked: boolean
  replies: Reply[]
  likeId?: number
}

interface Reply {
  id: number
  user: string
  userId: number
  avatar: string
  content: string
  time: string
  likes: number
  isLiked: boolean
  replyTo?: string
  replyToUserId?: number
  likeId?: number
}

interface UserInfo {
  avatar: string;
  nickname: string;
  userId: number;
}

// 状态管理
const isCommentsVisible = ref(false)
const commentText = ref('')
const articleData = ref<Article | null>(null)
const replyTo = ref<Comment | null>(null)
const comments = ref<Comment[]>([])
const isRefreshing = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const isLoading = ref(false)
const isLoadingComments = ref(false)
const isInputFocus = ref(false)
const articleId = ref<number>(0)
const isLoggedIn = ref(false)
const userInfo = ref<UserInfo | null>(null)
const commentTotal = ref(0)
const currentParentComment = ref<Comment | null>(null)

// 常量
const defaultImage = 'https://ai-public.mastergo.com/ai/img_res/3dd10a1c6c72a4ab667695de581c0164.jpg'

// 敏感词列表（实际使用时可从后端获取或扩展更多）
const sensitiveWords = [
  '暴力', '色情', '赌博', '诈骗', '政治', '黄色', '血腥',
  '违法', '犯罪', '毒品', '自杀', '恐怖', '歧视', '谩骂',
  '辱骂', '操', '艹', '草', '滚', '混蛋', '傻逼', '妈的'
]

// 检测文本是否包含敏感词
const hasSensitiveWords = (text: string): { hasSensitive: boolean, word?: string } => {
  if (!text) return { hasSensitive: false }
  
  const lowerText = text.toLowerCase()
  for (const word of sensitiveWords) {
    if (lowerText.includes(word)) {
      return { hasSensitive: true, word }
    }
  }
  
  return { hasSensitive: false }
}

// 返回上一页
const handleBack = () => {
  uni.navigateBack()
}

// 返回首页
const handleHome = () => {
  uni.switchTab({
    url: '/pages/index/index'
  })
}

// 切换评论区显示
const toggleComments = () => {
  isCommentsVisible.value = !isCommentsVisible.value
}

// 处理图片加载错误
const handleImageError = () => {
  uni.showToast({
    title: '图片加载失败',
    icon: 'none'
  })
}

// 检查是否可以删除评论
const canDelete = (comment: Comment): boolean => {
  // 判断评论是否是当前用户发布的
  return isCurrentUser(comment.userId)
}

// 格式化文章内容，处理换行和分点
const formattedContent = computed(() => {
  if (!articleData.value?.moredescription) return ''
  
  // 1. 替换\\n为实际的换行符
  let content = articleData.value.moredescription.replace(/\\n/g, '\n')
  
  // 2. 将换行符转换为HTML的<br>标签
  content = content.replace(/\n/g, '<br>')
  
  // 3. 根据数字+.开头的行添加样式（识别分点内容）
  content = content.replace(/(\d+\.)/g, '<strong>$1</strong>')
  
  return content
})

// 从接口获取文章详情
const fetchArticleData = async () => {
  if (!articleId.value) {
    uni.showToast({
      title: '无效的文章ID',
      icon: 'none'
    })
    return
  }

  try {
    isLoading.value = true
    
    // 调用接口获取文章详情
    uni.request({
      url: `${apiBaseUrl}/health/guides/selectMoreDescriptionById`,
      method: 'POST',
      data: {
        id: articleId.value
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          const data = res.data.result
          
          // 处理返回数据
          articleData.value = {
            id: data.id,
            title: data.title,
            moredescription: data.more_description, // 后端返回的是more_description，前端使用moredescription
            image: data.image,
            time: data.time,
            views: data.views
          }
          
          // 获取评论数据
          fetchComments()
        } else {
          uni.showToast({
            title: res.data.msg || '获取文章失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('请求失败', err)
        uni.showToast({
          title: '网络请求失败，请检查网络',
          icon: 'none'
        })
      },
      complete: () => {
        isLoading.value = false
      }
    })
  } catch (error) {
    console.error('获取文章失败', error)
    isLoading.value = false
    uni.showToast({
      title: '获取文章失败',
      icon: 'none'
    })
  }
}

// 从后端获取评论数据
const fetchComments = () => {
  if (!articleId.value) return
  
  isLoadingComments.value = true
  
  // 获取当前登录用户的ID
  const userId = uni.getStorageSync("id")
  
  // 构建请求参数
  const params = {
    postId: articleId.value,
    offset: 0,
    limit: 10,
    userId: userId
  }
  
  // 调用接口获取评论
  uni.request({
    url: `${apiBaseUrl}/patient/user/comment/getCommentsByPostId`,
    method: 'POST',
    data: params,
    success: (res) => {
      if (res.statusCode === 200 && res.data.code === 200) {
        const data = res.data.result
        
        // 更新评论总数和是否有更多评论
        commentTotal.value = data.total || 0
        hasMore.value = data.hasMore || false
        
        // 转换评论数据格式以匹配组件使用
        const formattedComments = data.comments.map((item: any) => {
          // 转换回复数据格式
          const topReplies = item.topReplies || []
          const formattedReplies = topReplies.map((reply: any) => {
            // 确保将userId转换为数字类型
            return {
              id: reply.id,
              user: reply.nickname,
              userId: Number(reply.user_id), // 确保是数字类型
              avatar: reply.avatar || defaultImage,
              content: reply.content,
              time: formatDateTime(reply.create_time),
              likes: reply.likeCount || 0,
              isLiked: reply.isLiked || false,
              replyToUserId: reply.reply_to_user_id ? Number(reply.reply_to_user_id) : undefined,
              likeId: reply.likeId // 添加点赞ID
            }
          })
          
          // 返回转换后的评论数据
          return {
            id: item.id,
            user: item.user_nickname,
            userId: Number(item.patient_user_id), // 确保是数字类型
            avatar: item.user_photo || defaultImage,
            content: item.content,
            time: formatDateTime(item.create_time),
            likes: item.likeCount || 0,
            isLiked: item.isLiked || false,
            replies: formattedReplies,
            likeId: item.likeId // 添加点赞ID
          }
        })
        
        comments.value = formattedComments
      } else {
        uni.showToast({
          title: res.data.msg || '获取评论失败',
          icon: 'none'
        })
      }
    },
    fail: (err) => {
      console.error('获取评论失败', err)
      uni.showToast({
        title: '网络请求失败，获取评论失败',
        icon: 'none'
      })
    },
    complete: () => {
      isLoadingComments.value = false
    }
  })
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return ''
  
  try {
    const date = new Date(dateTimeStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}`
  } catch (error) {
    console.error('日期格式化错误', error)
    return dateTimeStr
  }
}

// 获取路由参数中的文章ID
const getArticleIdFromRoute = () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.options || {}
  
  if (options.id) {
    articleId.value = parseInt(options.id)
  } else {
    // 测试环境下，如果没有传入ID，使用默认值
    articleId.value = 2 // 默认使用ID为2的文章用于测试
    console.warn('未获取到文章ID，使用默认ID:', articleId.value)
  }
}

// 加载数据
const loadData = async () => {
  try {
    isLoading.value = true
    await fetchArticleData()
  } catch (error) {
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

// 页面加载
onMounted(() => {
  getArticleIdFromRoute()
  loadData()
  checkLoginStatus()
})

// 下拉刷新
const onRefresh = async () => {
  try {
    isRefreshing.value = true
    currentPage.value = 1
    hasMore.value = true
    await loadData()
  } finally {
    isRefreshing.value = false
  }
}

// 加载更多
const loadMore = async () => {
  if (isLoading.value || !hasMore.value) return
  
  try {
    isLoading.value = true
    // 模拟加载更多数据
    await new Promise(resolve => setTimeout(resolve, 500))
    currentPage.value++
    // 这里可以调用API获取更多评论
    hasMore.value = currentPage.value < 3 // 模拟只有3页数据
  } catch (error) {
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

// 修改处理回复评论方法，添加父评论参数
const handleReply = (comment: Comment | Reply, parentComment?: Comment) => {
  // 检查登录状态
  if (!isLoggedIn.value) {
    showLoginTip()
    return
  }
  
  replyTo.value = comment as Comment
  if (parentComment) {
    currentParentComment.value = parentComment
  } else {
    currentParentComment.value = null
  }
  
  commentText.value = ''
  // 延迟设置焦点，确保输入框已经渲染
  setTimeout(() => {
    isInputFocus.value = true
  }, 100)
}

// 修改发送评论方法
const sendComment = () => {
  // 检查登录状态
  if (!isLoggedIn.value) {
    showLoginTip()
    return
  }
  
  if (!commentText.value.trim()) {
    uni.showToast({
      title: '请输入评论内容',
      icon: 'none'
    })
    return
  }
  
  // 敏感词检测
  const sensitiveCheck = hasSensitiveWords(commentText.value)
  if (sensitiveCheck.hasSensitive) {
    uni.showToast({
      title: `评论包含敏感词"${sensitiveCheck.word}"，请修改后重试`,
      icon: 'none',
      duration: 2000
    })
    return
  }

  // 确保有用户信息
  if (!userInfo.value) {
    uni.showToast({
      title: '用户信息获取失败',
      icon: 'none'
    })
    return
  }
  
  // 获取当前时间
  const now = new Date().toISOString()
  
  // 获取用户ID
  const userId = uni.getStorageSync("id")
  
  // 准备评论数据
  let commentData: any = {
    postId: articleId.value,
    userId: userId,
    content: commentText.value
  }
  
  // 如果是回复其他评论
  if (replyTo.value) {
    if (currentParentComment.value) {
      // 回复中的回复
      commentData.commentId = currentParentComment.value.id
      
      commentData.replyToReplyId = replyTo.value.id
    } else {
      // 直接回复评论
      commentData.commentId = replyTo.value.id
    }
  }
  
  // 调用发送评论/回复的API
  uni.request({
    url: replyTo.value 
      ? `${apiBaseUrl}/patient/user/reply/add` 
      : `${apiBaseUrl}/patient/user/comment/add`,
    method: 'POST',
    data: commentData,
    success: (res) => {
      if (res.statusCode === 200 && res.data.code === 200) {
        // 清空输入
        commentText.value = ''
        replyTo.value = null
        currentParentComment.value = null
        isInputFocus.value = false
        
        // 重新获取评论数据
        fetchComments()
        
        // 显示评论成功提示
        uni.showToast({
          title: '发布成功',
          icon: 'success',
          duration: 1500
        })
      } else {
        uni.showToast({
          title: res.data.msg || '评论失败',
          icon: 'none'
        })
      }
    },
    fail: () => {
      uni.showToast({
        title: '网络错误，评论失败',
        icon: 'none'
      })
    }
  })
}

// 修改取消回复方法
const cancelReply = () => {
  replyTo.value = null
  currentParentComment.value = null
  commentText.value = ''
  isInputFocus.value = false
}

// 修改点赞评论方法
const handleLike = (comment: Comment | Reply) => {
  // 检查登录状态
  if (!isLoggedIn.value) {
    showLoginTip()
    return
  }
  
  // 获取当前用户ID
  const userId = uni.getStorageSync("id")
  if (!userId) {
    uni.showToast({
      title: '用户信息不完整',
      icon: 'none'
    })
    return
  }
  
  // 确定目标类型和ID
  const isReply = !('replies' in comment)
  const targetType = isReply ? 'reply' : 'comment'
  const targetId = comment.id
  
  // 如果已经点赞，执行取消点赞
  if (comment.isLiked) {
    // 取消点赞需要点赞记录ID
    if (!comment.likeId) {
      // 如果没有点赞ID，先获取
      uni.request({
        url: `${apiBaseUrl}/patient/user/like/getLikeId`,
        method: 'POST',
        data: {
          patientUserId: userId,
          targetId: targetId,
          targetType: targetType
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 200) {
            const likeId = res.data.result
            // 使用获取到的likeId执行取消点赞
            cancelLike(likeId, comment)
          } else {
            uni.showToast({
              title: res.data.msg || '操作失败',
              icon: 'none'
            })
          }
        },
        fail: () => {
          uni.showToast({
            title: '网络错误，操作失败',
            icon: 'none'
          })
        }
      })
    } else {
      // 如果已有点赞ID，直接取消
      cancelLike(comment.likeId, comment)
    }
  } else {
    // 添加点赞
    addLike(userId, targetId, targetType, comment)
  }
}

// 添加点赞函数
const addLike = (userId: number, targetId: number, targetType: string, comment: Comment | Reply) => {
  uni.request({
    url: `${apiBaseUrl}/patient/user/like/add`,
    method: 'POST',
    data: {
      patientUserId: userId,
      targetId: targetId,
      targetType: targetType
    },
    success: (res) => {
      if (res.statusCode === 200 && res.data.code === 200) {
        // 保存返回的点赞ID，方便后续取消点赞使用
        comment.likeId = res.data.result
        // 更新UI
        comment.isLiked = true
        comment.likes += 1
        
        uni.showToast({
          title: '点赞成功',
          icon: 'none',
          duration: 1500
        })
      } else {
        uni.showToast({
          title: res.data.msg || '点赞失败',
          icon: 'none'
        })
      }
    },
    fail: () => {
      uni.showToast({
        title: '网络错误，操作失败',
        icon: 'none'
      })
    }
  })
}

// 取消点赞函数
const cancelLike = (likeId: number, comment: Comment | Reply) => {
  uni.request({
    url: `${apiBaseUrl}/patient/user/like/cancel?id=${likeId}`,
    method: 'POST',
    success: (res) => {
      if (res.statusCode === 200 && res.data.code === 200) {
        // 更新UI
        comment.isLiked = false
        comment.likes -= 1
        // 清除likeId
        comment.likeId = undefined
        
        uni.showToast({
          title: '已取消点赞',
          icon: 'none',
          duration: 1500
        })
      } else {
        uni.showToast({
          title: res.data.msg || '操作失败',
          icon: 'none'
        })
      }
    },
    fail: () => {
      uni.showToast({
        title: '网络错误，操作失败',
        icon: 'none'
      })
    }
  })
}

// 修改删除评论方法
const handleDelete = (comment: Comment) => {
  // 检查登录状态
  if (!isLoggedIn.value) {
    showLoginTip()
    return
  }
  
  // 获取当前用户ID
  const userId = uni.getStorageSync("id")
  if (!userId) {
    uni.showToast({
      title: '用户信息不完整',
      icon: 'none'
    })
    return
  }
  
  uni.showModal({
    title: '提示',
    content: '确定要删除这条评论吗？',
    success: (res) => {
      if (res.confirm) {
        // 调用删除评论的接口
        uni.request({
          url: `${apiBaseUrl}/patient/user/comment/delete`,
          method: 'POST',
          data: {
            replyId: comment.id,
            patientUserId: userId
          },
          success: (res) => {
            if (res.statusCode === 200 && res.data.code === 200) {
              const index = comments.value.findIndex(c => c.id === comment.id)
              if (index > -1) {
                comments.value.splice(index, 1)
                commentTotal.value--
              }
              
              uni.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 1500
              })
            } else {
              uni.showToast({
                title: res.data.msg || '删除失败',
                icon: 'none'
              })
            }
          },
          fail: () => {
            uni.showToast({
              title: '网络错误，删除失败',
              icon: 'none'
            })
          }
        })
      }
    }
  })
}

// 添加删除回复的方法
const handleDeleteReply = (reply: Reply, parentComment: Comment) => {
  // 检查登录状态
  if (!isLoggedIn.value) {
    showLoginTip()
    return
  }
  
  // 获取当前用户ID
  const userId = uni.getStorageSync("id")
  if (!userId) {
    uni.showToast({
      title: '用户信息不完整',
      icon: 'none'
    })
    return
  }
  
  uni.showModal({
    title: '提示',
    content: '确定要删除这条回复吗？',
    success: (res) => {
      if (res.confirm) {
        // 调用删除回复的接口
        uni.request({
          url: `${apiBaseUrl}/patient/user/reply/delete?replyId=${reply.id}`,
          method: 'POST',
          success: (res) => {
            if (res.statusCode === 200 && res.data.code === 200) {
              // 从父评论的回复列表中移除此回复
              const index = parentComment.replies.findIndex(r => r.id === reply.id)
              if (index > -1) {
                parentComment.replies.splice(index, 1)
              }
              
              uni.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 1500
              })
            } else {
              uni.showToast({
                title: res.data.msg || '删除失败',
                icon: 'none'
              })
            }
          },
          fail: () => {
            uni.showToast({
              title: '网络错误，删除失败',
              icon: 'none'
            })
          }
        })
      }
    }
  })
}

// 处理输入框获得焦点
const handleInputFocus = () => {
  isInputFocus.value = true
}

// 处理输入框失去焦点
const handleInputBlur = () => {
  isInputFocus.value = false
}

// 添加检查登录状态函数
const checkLoginStatus = () => {
  try {
    const token = uni.getStorageSync('token')
    if (token) {
      isLoggedIn.value = true
      
      // 从本地存储中读取用户信息
      const userInfoData = uni.getStorageSync('userInfo')
      if (userInfoData) {
        try {
          userInfo.value = JSON.parse(userInfoData)
          console.log('已获取用户信息:', userInfo.value)
        } catch (e) {
          console.error('解析用户信息失败', e)
          userInfo.value = null
        }
      } else {
        console.warn('已登录但未找到用户信息')
        userInfo.value = null
      }
    } else {
      isLoggedIn.value = false
      userInfo.value = null
    }
  } catch (e) {
    console.error('获取登录状态失败', e)
    isLoggedIn.value = false
    userInfo.value = null
  }
}

// 添加登录提示函数
const showLoginTip = () => {
  uni.showModal({
    title: '提示',
    content: '您需要登录后才能进行评论',
    confirmText: '去登录',
    success: (res) => {
      if (res.confirm) {
        // 跳转到登录页面 (user是tabBar页面，必须使用switchTab)
        uni.switchTab({
          url: '/pages/user/user'
        })
      }
    }
  })
}

// 修改评论区标题显示的评论数量
const commentCountDisplay = computed(() => {
  return `评论区 (${commentTotal.value}条评论)`
})

// 判断是否为当前用户
const isCurrentUser = (userId: number | undefined) => {
  if (!userId) return false
  const currentUserId = Number(uni.getStorageSync("id"))
  return currentUserId === userId
}

// 判断是否为自己回复自己
const isReplyingSelf = (reply: Reply, comment: Comment) => {
  // 如果回复中有replyToUserId字段，则与当前用户ID比较
  if (reply.replyToUserId) {
    return isCurrentUser(reply.userId) && isCurrentUser(reply.replyToUserId)
  }
  // 如果是回复评论，则比较评论用户ID
  return isCurrentUser(reply.userId) && isCurrentUser(comment.userId)
}
</script>

<style lang="scss">
page {
  height: 100%;
}

.container {
  min-height: 100vh;
  background-color: #f5f8ff;
}

.header {
  background-color: #fff;
  padding: 10px 15px;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left, .right {
  display: flex;
  gap: 15px;
}

.title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.content {
  height: calc(100vh - 60px);
  padding: 15px;
  box-sizing: border-box;
}

.article-list {
  background-color: #fff;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 15px;
}

.article-header {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
  padding: 0 5px;
}

.article-image {
  width: 120px;
  height: 80px;
  border-radius: 8px;
}

.article-info {
  flex: 1;
}

.article-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.article-meta {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #999;
}

.article-content {
  padding: 0 5px;
  
  .content-text {
    font-size: 14px;
    line-height: 1.6;
    color: #666;
    text-align: justify;
    
    strong {
      color: #333;
      font-weight: 600;
      display: inline-block;
      margin-top: 8px;
    }
    
    br {
      display: block;
      content: "";
      margin-top: 8px;
    }
  }

  .content-image {
    width: 100%;
    height: 200px;
    border-radius: 8px;
    margin: 15px 0;
  }
}

.comments-section {
  margin-top: 20px;
  border-top: 1px solid #eee;
  padding-top: 15px;
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.comments-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.comment-list {
  .comment-item {
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
  }

  .comment-main {
    display: flex;
    gap: 10px;
    padding: 5px;
    border-radius: 8px;
    transition: background-color 0.2s;
    
    &:active {
      background-color: #f5f5f5;
    }
  }

  .comment-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
  }

  .comment-content {
    flex: 1;
  }

  .comment-user {
    font-size: 14px;
    font-weight: 500;
    color: #333;
    margin-bottom: 4px;
    
    .user-self-tag {
      font-size: 12px;
      color: #999;
      font-weight: normal;
      margin-left: 2px;
    }
  }

  .comment-text {
    font-size: 14px;
    color: #333;
    line-height: 1.5;
  }

  .comment-time {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
    margin-bottom: 4px;
  }
}

.comment-actions {
  display: flex;
  gap: 15px;
  margin-top: 4px;
  font-size: 13px;
  color: #999;

  .action-btn {
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .reply-btn, .delete-btn {
    color: #4a90e2;
  }
}

.replies-list {
  margin-left: 50px;
  margin-top: 10px;
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    left: -20px;
    top: 0;
    height: 100%;
    width: 1px;
    background-color: #eee;
  }

  .reply-item {
    margin-bottom: 10px;
    position: relative;
    
    &::before {
      content: '';
      position: absolute;
      left: -20px;
      top: 20px;
      width: 15px;
      height: 1px;
      background-color: #eee;
    }
    
    &:last-child {
      margin-bottom: 0;
    }
  }

  .reply-main {
    display: flex;
    gap: 10px;
    padding: 5px;
    border-radius: 8px;
    transition: background-color 0.2s;
    
    &:active {
      background-color: #f5f5f5;
    }
  }

  .reply-avatar {
    width: 30px;
    height: 30px;
    border-radius: 50%;
  }

  .reply-content {
    flex: 1;
  }

  .reply-user {
    font-size: 14px;
    font-weight: 500;
    color: #333;
    
    .user-self-tag {
      font-size: 12px;
      color: #999;
      font-weight: normal;
      margin-left: 2px;
    }
  }

  .reply-text {
    font-size: 13px;
    color: #333;
    line-height: 1.5;
    
    .reply-arrow {
      color: #999;
      margin-right: 4px;
    }
    
    .reply-target {
      color: #4a90e2;
      font-weight: 500;
      margin-right: 4px;
    }
  }

  .reply-time {
    font-size: 12px;
    color: #999;
    margin-top: 2px;
    margin-bottom: 2px;
  }
  
  .reply-actions {
    display: flex;
    gap: 15px;
    margin-top: 4px;
    font-size: 12px;
    color: #999;
    
    .like-btn {
      display: flex;
      align-items: center;
      gap: 4px;
    }
    
    .reply-btn {
      color: #4a90e2;
    }
  }
}

.comment-input {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
  position: sticky;
  bottom: 0;
  background-color: #fff;
  z-index: 10;

  .reply-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    padding: 8px 12px;
    background-color: #f5f8ff;
    border-radius: 8px;
    font-size: 13px;
    color: #666;

    .cancel-reply {
      color: #4a90e2;
      padding: 4px 8px;
      border-radius: 4px;
      background-color: rgba(74, 144, 226, 0.1);
    }
  }

  .input-wrapper {
    display: flex;
    gap: 10px;
    padding: 0 5px 10px;
  }

  .input-box {
    flex: 1;
    height: 40px;
    border: 1px solid #eee;
    border-radius: 20px;
    padding: 0 15px;
    font-size: 14px;
    background-color: #fff;
  }

  .send-button {
    width: 60px;
    height: 40px;
    background-color: #4a90e2;
    color: #fff;
    border-radius: 20px;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: center;

    &:disabled {
      background-color: #ccc;
    }
  }
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  color: #999;
  font-size: 14px;
  gap: 10px;
}

.load-more {
  text-align: center;
  padding: 15px 0;
  color: #999;
  font-size: 14px;
}
</style>
